import json
import socket
import struct
import threading
from SocketServer import ThreadingTCPServer
try:
    import fcntl
except ImportError:
    fcntl = None
import mon_center_logger

logger = mon_center_logger.instance()

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

def encode(data):
    return json.dumps(data)

def decode(data):
    return json.loads(data)

def error_handler():
    pass


def threadinglize(target_, tName=None, isDaemon_=True):
    def func_(*args_, **kwargs_):
        t = threading.Thread(target=target_, args=args_, kwargs=kwargs_)
        if isDaemon_:
            t.setDaemon(True)
        if tName:
            t.setName(tName)
        else:
            t.setName(target_.__name__)
        t.start()
    return func_

def getDictDeeply(dict_, keys):
    ret = dict_
    if type(keys) is str:
        ret = dict_[keys]
    else:
        keys = list(keys)
        for i in keys:
            ret = ret[i]

    return ret

def setDictDeeply(dict_, keys, val, createMidNodes=False):
    if type(keys) is str:
        dict_[keys] = val
    else:
        keys = list(keys)
        midKeys = keys[0:-1]
        theKey = keys[-1]
        sub = dict_
        for i in midKeys:
            try:
                sub = sub[i]
            except KeyError, e:
                if createMidNodes:
                    sub[i] = {}
                    sub = sub[i]
                else:
                    raise
        sub[theKey] = val

def delDictDeeply(dict_, keys):
    if type(key) is str:
        del dict_[key]
    else:
        keys = list(keys)
        midKeys = keys[0:-1]
        theKey = keys[-1]
        sub = dict_
        for i in midKeys:
            sub = sub[i]
        del sub[theKey]

